<?php
/*   
编辑者:写php的黄瓜兄
创建日期:2019.4.22
创建控制器/方法:提现
*/

namespace app\inter\controller;
use think\Config;
use  think\Controller;
use think\Db;

class Exam extends Controller 
{
  
    //预约考试
     public  function  apot_exam()
     {
       
       //接受数据
       $param=$this->request->param();
//        return json(['data'=>$param, 'msg'=>'考试预约成功', 'state'=>10000]);
       //考试计划表
       $data['create_time']=time();//创建时间
       $data['status']=0;//考试未进行
/*
         //时间转换
//         $day_num = ($param['week']+1)*7+$param['day']+1;
         $day_num = (1+1)*7+1+1;
         $s_time = '2019-02-18 00:00:00';
         $z_time = date("Y-m-d", strtotime("+{$day_num} days", strtotime($s_time)));
*/
       
        //设定学期开始的时间是那一天
        $star_day="2019-02-18 00:00:00";
        $unixtime=strtotime($star_day);
        $time=(($param['week'])*7+($param['day']))*24*60*60;
        $z_time=$unixtime+$time;
        $z_time = date("Y-m-d",$z_time);
      
    /*     echo $unixtime.'/'; 
       echo $time.'/';
       echo $s_time;exit();*/
       //将数据插入数据库
         $exam_plan_insert = [
             'title' => $param['title'],
             'week' => $param['week'],
             'day' => $param['day'],
             'test_paper_id' => $param['paper_id'],
//             'start_date' => $param['start_date'],
             'time_type' => $param['time_type'],
             'length_time' => $param['length_time'],
             'start_time' => $z_time." {$param['start_time']}:00",
             'end_time' => $z_time." {$param['end_time']}:00",
             'subject_id' => $param['subject_id'],
             'scope' => $param['scope'],
             'num' => $param['people'],
             'status' => 1,
             'crt_user' => $param['crt_user'],
             'crt_time' => time(),
         ];
         Db::startTrans();
         try{
             $exam_plan_id = Db::table('exam_plan')->insert($exam_plan_insert, false, true);

             if($exam_plan_id){

                 if($param['scope'] == 0){
                     $exam_plan_class_insert = [
                         'class_id' => $param['class_id'],
                         'exam_plan_id' => $exam_plan_id,
                         'crt_user' => $param['crt_user'],
                     ];

                     $exam_plan_class_id = Db::table('exam_plan_class')->insert($exam_plan_class_insert, false, true);
                     if(!$exam_plan_class_id) return json(['data'=>'', 'msg'=>'考试预约失败', 'state'=>10002]);
                     //考试计划关系插入
                     $student_list = Db::table('rel_class_user')->where([
                         'class_id' => $param['class_id']
                     ])->select();

                     foreach($student_list as &$item){
                         $exam_plan_student_inset = [
                             'student_id' => $item['user_id'],
                             'exam_plan_id' => $exam_plan_id,
                             'class_id' => $param['class_id'],
                         ];
                         $ret1 = Db::table('exam_plan_student')->insert($exam_plan_student_inset);

                         if(!$ret1)   return json(['data'=>'', 'msg'=>'考试预约失败', 'state'=>10002]);
                     }
                 }else{
                     $class_data = Db::table('app_class')->select();
                     foreach($class_data as $k => $v){
                         $exam_plan_class_insert = [
                             'class_id' => $v['class_id'],
                             'exam_plan_id' => $exam_plan_id,
                             'crt_user' => $param['crt_user'],
                         ];

                         $exam_plan_class_id = Db::table('exam_plan_class')->insert($exam_plan_class_insert, false, true);
                         if(!$exam_plan_class_id) return json(['data'=>'', 'msg'=>'考试预约失败', 'state'=>10002]);
                         //考试计划关系插入
                         $student_list = Db::table('rel_class_user')->where([
                             'class_id' => $v['class_id']
                         ])->select();

                         foreach($student_list as &$item){
                             $exam_plan_student_inset = [
                                 'student_id' => $item['user_id'],
                                 'exam_plan_id' => $exam_plan_id,
                                 'class_id' => $v['class_id'],
                             ];
                             $ret1 = Db::table('exam_plan_student')->insert($exam_plan_student_inset);

                             if(!$ret1)   return json(['data'=>'', 'msg'=>'考试预约失败', 'state'=>10002]);
                         }
                     }

                 }



             }else{

                 return json(['data'=>'', 'msg'=>'考试预约失败', 'state'=>10002]);
             }
             Db::commit();
         }catch(\Exception $e){
             Db::rollback();
             return json(['data'=>'', 'msg'=>'考试预约失败-2', 'state'=>10002]);
         }

         return json(['data'=>'', 'msg'=>'考试预约成功', 'state'=>10000]);
         //exam_plan_student

         //exam_plan_class

        
       
     }

   public function EditExamPlan(){
       $param = $this->request->param();
       $data = $param;
       unset($data['id']);
       $update = Db::table('exam_plan')->where(['id'=> $param['id']] )->update($data);
       if($update){
           return json(['data'=>'', 'msg'=>'修改成功', 'state'=>10000]);
       }else{
           return json(['data'=>'', 'msg'=>'修改失败', 'state'=>10001]);
       }
   }
    //获取考试科目
    public function get_subject(){
      
     //$subject= Db::name('subject')->select();
      
     $subject=[
     '1'=>'语文',
     '2'=>'数学',
     '3'=>'英语',
     '4'=>'化学',
     ];
    
     if($subject){
            
              return json(['data'=>$subject, 'msg'=>'查询成功', 'state'=>10001]);
          }else{
        
              return json(['data'=>'', 'msg'=>'无数据', 'state'=>10001]);
        }
    }
  
     //获取考试班级
    public function get_class(){
        $param = $this->request->param();
        if(empty($param['crt_user'])) return  json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        $list = Db::table('app_class')->field('class_id, class_name')
            ->where(['s_state' => 1, 's_creator_id' => $param['crt_user']])->select();

     if($list){
              return json(['data'=>$list, 'msg'=>'查询成功', 'state'=>10000]);
          }else{
        
              return json(['data'=>'', 'msg'=>'无数据', 'state'=>10001]);
        }
    }
       
  
     //获取考试年级
    public function get_grade(){
      
     //$grade= Db::name('grade')->select();
      
     $grade=Config::get('grade');
    
     if($grade){
            
              return json(['data'=>$grade, 'msg'=>'查询成功', 'state'=>10001]);
          }else{
        
              return json(['data'=>'', 'msg'=>'无数据', 'state'=>10001]);
        }
    }
       
     //获取考试年级
    public function get_exam_paper(){
        $param = $this->request->param();
        $scope = Config::get('scope');
        $degree = Config::get('degree');
        if(!isset($param['subject_id'])
            || empty($param['crt_user'])
            ) return  json(['data'=>'', 'msg'=>'参数不全', 'state'=>10002]);
        $grade = Config::get('grade');
        $subject = Config::get('subject');
        $sql = "SELECT tp.id, tp.title, tp.grade_id, tp.subject_id,
        tp.crt_time, u.name as teacher, tp.degree, tp.scope FROM test_paper as tp
LEFT JOIN sys_user as u ON u.user_id=tp.crt_user
WHERE tp.`state`=2 AND tp.subject_id={$param['subject_id']}
AND tp.crt_user={$param['crt_user']}";
        if(!empty($param['grade_id']))  $sql .= " AND tp.grade_id={$param['grade_id']}";
            $list = Db::query($sql);
        if($list){
            foreach($list as &$item){
                isset($grade[$item['grade_id']]) ? $item['grade_label'] = $grade[$item['grade_id']] : $item['grade_label']='';
                isset($subject[$item['subject_id']]) ? $item['subject_label'] = $subject[$item['subject_id']] : $item['subject_label'] = '';
                $item['crt_time'] = date('Y-m-d', $item['crt_time']);
                $item['scope_label'] = isset($scope[$item['scope']])?$scope[$item['scope']]:'';
                $item['degree_label'] = $degree[$item['degree']];
            }
            return json(['data'=>$list, 'msg'=>'success', 'state'=>10000]);
        }else{
            return  json(['data'=>'', 'msg'=>'未找到', 'state'=>10003]);
        }

    }

    public function getInitParam(){
        $subject = Config::get('subject');
        $grade = Config::get('grade');
        $degree = Config::get('degree');
        $scope = Config::get('scope');
        $week = Config::get('week');
        $topic_type = Config::get('topic_type');
        $ke_time = [
            [
                'v' => 1,
                'start_time' => date('Y-m-d 08:00:00'),
                'end_time' => date('Y-m-d 09:00:00'),
                'time_length' => '60分钟'
            ],
            [
                'v' => 2,
                'start_time' => date('Y-m-d 09:00:00'),
                'end_time' => date('Y-m-d 10:00:00'),
                'time_length' => '60分钟'
            ],
            [
                'v' => 3,
                'start_time' => date('Y-m-d 11:00:00'),
                'end_time' => date('Y-m-d 12:00:00'),
                'time_length' => '60分钟'
            ],
            [
                'v' => 4,
                'start_time' => date('Y-m-d 13:00:00'),
                'end_time' => date('Y-m-d 14:00:00'),
                'time_length' => '60分钟'
            ],
            [
                'v' => 5,
                'start_time' => date('Y-m-d 15:00:00'),
                'end_time' => date('Y-m-d 16:00:00'),
                'time_length' => '60分钟'
            ],
            [
                'v' => 6,
                'start_time' => date('Y-m-d 17:00:00'),
                'end_time' => date('Y-m-d 18:00:00'),
            ],
            [
                'v' => 7,
                'start_time' => date('Y-m-d 08:00:00'),
                'end_time' => date('Y-m-d 09:00:00'),
                'time_length' => '60分钟'
            ],
            [
                'v' => 8,
                'start_time' => date('Y-m-d 19:00:00'),
                'end_time' => date('Y-m-d 20:00:00'),
                'time_length' => '60分钟'
            ],
        ];
        $data = [
            'subject' => $subject,
            'grade' => $grade,
            'degree' => $degree,
            'scope' => $scope,
            'week' => $week,
            'topic_type' => $topic_type,
            'lesson' => $ke_time,
            'teacher_subject_id' => 1,
            'template_url' => "/testt.docx"
        ];
        return json(['data' => $data, 'msg' => 'success', 'state' => 10000]);
    }

    public function getExamPlanList(){
        $param = $this->request->param();
        $where = ' 1=1';

        if(empty($param['scope'])) $where .= " and b.scope={$param['scope']}";
        if(isset($param['state'])) $where .= " and b.status={$param['state']}";
        if(!empty($param['keyword'])) $where .= ' and b.title like "%' . $param['keyword'] . '%"';
        $sql = "SELECT a.*,b.title,c.class_name,b.start_date,b.scope,b.test_paper_id,
b.start_time, b.end_time  FROM `exam_plan_class` as a
LEFT JOIN exam_plan as b ON b.id=a.exam_plan_id
LEFT JOIN app_class AS c ON c.class_id=a.class_id WHERE ";
        if($where) $sql .= $where;
        $total_num = count(Db::query($sql));
        $page = isset($param['page'])?$param['page']:1;
        $num = Config::get('page_count');
        $s_page = ($page-1)*$num;
        $e_page = $page*$num;
        $sql .= " LIMIT {$s_page},{$e_page} ";

        $list = Db::query($sql);
        $scope = Config::get('scope');
        foreach($list as &$item){
            $class_count = Db::table('rel_class_user')->where([
                'class_id' => $item['class_id']
            ])->count();
            $item['class_count'] = $class_count;
            $count = Db::table('exam_plan_student')->where([
                'exam_plan_id' => $item['exam_plan_id'],
                'class_id' => $item['class_id']
            ])->count();
            $item['complete_count'] = $count;
            $item['scope_label'] = $scope[$item['scope']];
            $item['rate'] = number_format($count/$class_count, 2)*100 ."%";
            $date = date('m-d');
            $now_y = date('Y');
            if($date<='09-01'){
                $y = $now_y-1;
                $item['class_xq'] = $y . "-" . $now_y ."学年下学期";
            }else{
                $y = $now_y+1;
                $item['class_xq'] = $now_y . "-" . $y ."学年上学期";
            }
            $test_paper = Db::table('test_paper')->where(['id' => $item['test_paper_id']])->find();
            $item['test_paper_title'] =$test_paper['title'];
            $item['time'] = date("H:i", strtotime($item['start_time'])) . "~" . date("H:i", strtotime($item['end_time']));
        }
        return json(['page_num' => ceil($total_num/Config::get('page_count')),'data' => $list, 'msg' => 'success', 'state' => 10000]);
    }


    public function getUser(){
        $param = $this->request->param();
        $data = Db::table('sys_user')->where(['user_id' => $param['crt_user']])->find();
        if($data){
            return json(['data' => $data, 'msg' => 'success', 'state' => 10000]);
        }else{
            return json(['msg' => 'fail', 'state' => 10001]);
        }
    }

    public function collect(){
        $param = $this->request->param();
        $result = Db::table('collect')->where([
            'uid' => $param['crt_user'],
            'test_paper_id' => $param['test_paper_id'],
        ])->find();
        if(!$result){
            Db::table('collect')->insert([
                'uid' => $param['crt_user'],
                'test_paper_id' => $param['test_paper_id'],
                'create_time' => date('Y-m-d H:i:s'),
                'status' => 1
            ]);
        }else{
            Db::table('collect')->where(['id' => $result['id']])->update(['status' => 1]);
        }
        return json(['data' => '', 'msg' => 'success', 'state' => 10000]);
    }

    public function collectNO(){
        $param = $this->request->param();
        Db::table('collect')->where([
            'uid' => $param['crt_user'],
            'test_paper_id' => $param['test_paper_id'],
        ])->delete(true);
        return json(['data' => '', 'msg' => 'success', 'state' => 10000]);
    }

    public function help(){
        $param = $this->request->param();
        Db::table('exam_plan')->where(['id' => $param['exam_plan_id']])->update(['is_help' => $param['is_help']]);
        return json(['data' => '', 'msg' => 'success', 'state' => 10000]);
    }

    public function test(){

        $list = Db::table('correct')->select();
        foreach($list as $item){
            $ret = Db::table('topic_complete')->where(['id' => $item['topic_complete_id']])->find();
            Db::table('correct')->where(['id' => $item['id']])
                ->update([
                    'student_id' => $ret['student_id'],
                    'exam_plan_id' => $ret['exam_plan_id'],
                    'class_id' => $ret['class_id'],
                ]);
        }
        echo "success";
        exit();
//        $tmp = json_decode($s, true);
//        var_dump($tmp);exit();
        $list = Db::table('test_paper_topic')->where(['test_paper_id' => 211])->select();
        foreach($list as $k => $v){
            $student_data = Db::table('rel_class_user')->where(['class_id' => '0037c597e3f144cd9c7cd0756ea9090j'])->select();
            foreach($student_data as $item){
                $insert = [
                    'student_id' => $item['user_id'],
                    'exam_plan_id' => 82,
                    'topic_id' => $v['topic_id'],
                    'answer' => 'A',
                    'status' => 0,
                    'crt_time' => time(),
                    'class_id' => '0037c597e3f144cd9c7cd0756ea9090j',
                ];
                Db::table('topic_complete')->insert($insert);
            }
        }
    }
}